/*
 * Copyright © 2024-2025 Wenze Wei
 *
 * This file is part of StadionOS.
 *
 * This Source Code Form is subject to the terms of the GNU General Public License, v. 2.0.
 * You can obtain a copy of the GPL at
 * https://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 */

#include "../../include/fsd.h"

ssize_t Srcof(const char *file, const char *key, void *buf, size_t bufsize) {
    int fd = SXopen(file, "r", 0);
    if (fd < 0)
        return -1;

    char tempBuf[1024];
    ssize_t bytesRead;

    while ((bytesRead = Sread(fd, tempBuf, sizeof(tempBuf) - 1)) > 0) {
        tempBuf[bytesRead] = '\0';

        char *line = Sstrtok(tempBuf, "\n");
        while (line != NULL) {
            char *trimmedLine = line;
            while (*trimmedLine == ' ') trimmedLine++;

            char *equalSign = Sstrchr(trimmedLine, '=');
            if (equalSign != NULL) {
                *equalSign = '\0';

                if (Sstrncmp(trimmedLine, key, Sstrlen(key)) == 0) {
                    char *valueStart = equalSign + 1;

                    while (*valueStart == ' ') valueStart++;

                    char *valueEnd = valueStart;
                    while (*valueEnd != '\0' && *valueEnd != '\n') valueEnd++;

                    size_t valueLen = valueEnd - valueStart;

                    if (valueLen > bufsize - 1) {
                        valueLen = bufsize - 1;
                    }

                    Sstrncpy((char *)buf, valueStart, valueLen);
                    ((char *)buf)[valueLen] = '\0';

                    Sclose(fd);
                    return valueLen;
                }
            }

            line = Sstrtok(NULL, "\n");
        }
    }

    if (bytesRead < 0)
        perror("Sread");

    Sclose(fd);
    return -1;
}
